package com.umakr.ax.opt.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.umakr.ax.common.model.UserDetails;
import com.umakr.ax.common.model.UserRelation;
import com.umakr.ax.common.service.UserDetailsService;
import com.umakr.ax.common.service.UserRelationService;
import com.umakr.ax.security.model.User;
import com.umakr.ax.security.model.UserRole;
import com.umakr.ax.security.service.UserRoleService;
import com.umakr.ax.security.service.UserService;
import com.umakr.ax.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * @author umakr
 */
@Service
public class UserOptService {

    @Autowired
    UserService userService;
    @Autowired
    UserDetailsService userDetailsService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    UserRelationService userRelationService;


    public void addRsAdmin(String username, String password, String nickName,Long rsId) {
        if(username == null || "".equals(username)){
            return;
        }
        //先处理管理员账号,status默认为1开通 0冻结
        EntityWrapper<User> userWrapper = new EntityWrapper<>();
        userWrapper.eq("account",username);
        User user = userService.selectOne(userWrapper);
        if(user == null) {
            user = new User();
            user.setAccount(username);
            user.setRemark("电台管理员");
            user.setStatus(1);
            user.setPassword(WebUtil.getBean(BCryptPasswordEncoder.class).encode(password));
            userService.update(user);
            Date date = new Date();
            //添加用户明细
            UserDetails userDetails = new UserDetails();
            userDetails.setNickname(nickName);
            userDetails.setUserId(user.getId());
            userDetails.setCreateTime(date);
            userDetailsService.update(userDetails);
            //添加角色
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId((long) 2);
            userRoleService.update(userRole);
            //添加用户电台关系表
            UserRelation userRelation = new UserRelation();
            userRelation.setRsId(rsId);
            userRelation.setUserId(user.getId());
            userRelationService.update(userRelation);
        }else {
            if(password != null && !"".equals(password)){
                user.setPassword(WebUtil.getBean(BCryptPasswordEncoder.class).encode(password));
            }
            userService.update(user);
        }
    }
}
